package com.yesido.javabase.concurrent.threadpool;

import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author yesido
 * 允许核心线程过期的线程池
 */
public class CustomThreadPool {
    public static void main(String[] args) {
        int corePoolSize = 2; // 核心线程数
        int maximumPoolSize = 4; // 最大线程数
        long keepAliveTime = 10L; // 超时时间
        TimeUnit unit = TimeUnit.SECONDS; // 时间单位
        int queueCapacity = 10; // 队列大小

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                new LinkedBlockingQueue<>(queueCapacity));

        threadPoolExecutor.allowCoreThreadTimeOut(true); // 允许核心线程超时
        threadPoolExecutor.setKeepAliveTime(5L, TimeUnit.SECONDS); // 等待时间
        threadPoolExecutor.setThreadFactory(new CustomizableThreadFactory("yesdio-test-"));

        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略

        // 提交10个任务
        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            threadPoolExecutor.submit(() -> {
                System.out.println("Task " + finalI + " is running on thread " + Thread.currentThread().getName());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        // 关闭线程池
        threadPoolExecutor.shutdown();
    }
}
